package com.biz.primus.ms.oms.dao.repository;

import com.biz.primus.ms.oms.dao.po.OmsOrder;
import com.biz.primus.ms.oms.dao.po.OmsOrderItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @author yanweijin
 * @date 2017/11/3
 */
public interface OmsOrderRepository extends JpaRepository<OmsOrder, Long>,JpaSpecificationExecutor<OmsOrder> {


	/**
	 * 检查订单编号是否存在
	 * @param orderCode
	 * @return
	 */
	@Query("select count(o.id) from OmsOrder o where o.orderCode = ?1")
	int isExistOrder(String orderCode);


	/**
	 * 根据订单编号查订单
	 * @param orderCode
	 * @return
	 */
	OmsOrder findByOrderCode(String orderCode);

	/**
	 * 根据订单号查询id
	 * @param orderCode
	 * @return
	 */
	Long findIdByOrderCode(String orderCode);

	/**
	 * 根据用户ID查询历史订单总金额
	 * @param userId
	 * @return
	 */
	@Query("select count(o.paidAmount) from OmsOrder  o where o.userId =?1 ")
	Integer findAmountByUserId(Long userId);

	/**
	 * 根据用户ID查询订单总数
	 * @param userId
	 * @return
	 */
	@Query("select count(o) from OmsOrder  o where o.userId =?1 ")
	Integer findOrderCountByUserId(Long userId);
	/**
	 * 根据userId获取最后一条订单记录
	 * @param userId
	 * @return
	 */
	OmsOrder findTop1ByUserIdOrderByCreateTimestampDesc(Long userId);


	/**
	 * 根据订单id和item id查询item po
	 * @param orderId
	 * @param itemIds
	 * @return
	 */
	@Query("from OmsOrderItem i where i.order.id = ?1 and i.id in ?2")
	List<OmsOrderItem> findOrderItemsById(Long orderId, List<Long> itemIds);
}
